//
//  GSComomRegisterController.m
//  GSLoginDemo
//
//  Created by guoshikeji_a on 2018/7/27.
//  Copyright © 2018年 guoshikeji. All rights reserved.
//

#import "GSComomRegisterController.h"

#import "GSCommonLoginInputView.h"

#import "GSComomRegisterSMSVerifyController.h"

#import "NSString+RegexCategory.h"

//使用条款
#import "BCProtocolController.h"

//request
#import "BCCheckRegisterUserRequest.h"//校验用户是否注册请求
#import "BCPhoneCaptchaRequest.h"//请求发送手机验证码
#import "BCEmailCaptchaRequest.h"//请求发送邮箱验证码


@interface GSComomRegisterController ()

@property (nonatomic, strong) GSCommonLoginInputView *inputView;

/**
 *textView
 */
@property (nonatomic, strong) YYTextView *agreenTextView;

@end

@implementation GSComomRegisterController

- (void)viewDidLoad {
    [super viewDidLoad];
    //
    self.largeTitleLabel.text = GSLoginLocalized(@"Please enter your user name and password");
    //
    NSString *subPrefixStr = GSLoginLocalized(@"Registration stands for read and agree ");
    NSString *subSuffixStr = @"";//@"使用条款";
    NSString *subStr = [NSString stringWithFormat:@"%@%@",subPrefixStr,subSuffixStr];
    NSMutableAttributedString *attriText = [[NSMutableAttributedString alloc] initWithString:subStr];
    NSRange range = [subStr rangeOfString:subSuffixStr];
    if (range.location!=NSNotFound) {
        [attriText addAttributes:@{NSForegroundColorAttributeName:GSLOGIN_THEME_COLOR,NSFontAttributeName:self.subTitleLabel.font} range:range];
    }
    self.subTitleLabel.attributedText = attriText;
    self.subTitleLabel.alpha = 0;
    //
    self.agreenTextView = [YYTextView new];
    self.agreenTextView.textContainerInset = UIEdgeInsetsZero;
    self.agreenTextView.editable = false;
    [self.view addSubview:self.agreenTextView];
    [self.agreenTextView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.mas_equalTo(self.subTitleLabel);
        make.left.mas_equalTo(self.subTitleLabel);
        make.width.mas_equalTo(self.view).offset(-40.0);
        make.height.mas_equalTo(100);
    }];
    //使用条款
    NSMutableAttributedString *textViewAttri = [[NSMutableAttributedString alloc] initWithAttributedString:attriText];
    NSMutableAttributedString *attachment = nil;
    //
    QMUIButton *useTermsButton = [QMUIButton new];
    [useTermsButton setTitle:GSLoginLocalized(@"Terms Of Use") forState:UIControlStateNormal];
    [useTermsButton setTitleColor:GSLOGIN_THEME_COLOR forState:UIControlStateNormal];
    useTermsButton.titleLabel.font = self.subTitleLabel.font;
    [useTermsButton sizeToFit];
    [useTermsButton addTarget:self action:@selector(useTermsButtonDidClickedAction:) forControlEvents:UIControlEventTouchUpInside];
    //
    attachment = [NSMutableAttributedString yy_attachmentStringWithContent:useTermsButton contentMode:UIViewContentModeLeft attachmentSize:useTermsButton.frame.size alignToFont:useTermsButton.titleLabel.font alignment:YYTextVerticalAlignmentCenter];
    //
    [textViewAttri appendAttributedString:attachment];
    self.agreenTextView.attributedText = textViewAttri;
    //
    [self setupSubviews];
    //
    __weak typeof(self) wself = self;
    self.inputView.inputViewInvalidBlock = ^(BOOL valid) {
        if (wself.nextStepButton.enabled!=valid) {
            wself.nextStepButton.enabled = valid;
        }
    };
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}
- (void)setupSubviews {
    self.inputView = [GSCommonLoginInputView new];
    self.inputView.accountPlaceholder = GSLoginLocalized(@"Email address/phone number");
    [self.view addSubview:self.inputView];
    [self.inputView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.mas_equalTo(self.subTitleLabel.mas_bottom).offset(38.0);
        make.left.right.mas_equalTo(self.view);
        make.height.mas_equalTo([GSCommonLoginInputView defaultHeight]);
    }];
    //
    [self.view addSubview:self.nextStepButton];
    [self.nextStepButton mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.mas_equalTo(self.inputView.mas_bottom).offset(50.0);
        make.centerX.mas_equalTo(self.view);
        make.size.mas_equalTo([GSCommonLoginButton defaultSize]);
    }];
    self.nextStepButton.enabled = false;
}

#pragma mark - useTermsButtonDidClickedAction:
- (void)useTermsButtonDidClickedAction:(QMUIButton *)button {
    [self.view endEditing:true];
    //需要加语言
    NSString *useItems = APP_User_Item;
    NSString *lang = [BCLabguageSettingManager shared].requestLang;
    if (lang.length) {
        useItems = [useItems stringByAppendingFormat:@"?lang=%@",lang];
    }
    [BCProtocolController showFromController:self.navigationController protocolURLString:useItems];
}

#pragma mark -
- (void)nextStepButtonDidClickedAction {
    [self.view endEditing:true];
    if ([self checkInputData]) {
        [self requestRegisterUserCheckAction];
    }
}

#pragma mark - checkInputData
- (BOOL)checkInputData {
    //检查账户
    GSCCommonLoginAccountType type = [NSString gscLoginAccountTypeWithString:self.inputView.account];
    if (type==GSCCommonLoginAccountTypeUnknown) {
        NSString *errorMsg = GSLoginLocalized(@"phone or email format error");
        [QMUITips showError:errorMsg inView:self.view hideAfterDelay:[QMUITips smartDelaySecondsForTipsText:errorMsg]];
        return false;
    }
    //检查密码
    BOOL passwordInvalid = [NSString gsLoginPasswordRegex:self.inputView.password];
    if (!passwordInvalid) {
        NSString *errorTitleMsg = GSLoginLocalized(@"password format error");
        NSString *errorSub = GSLoginLocalized(@"Must be 6 to 20 English letters, Numbers, or characters(except space), and letters, Numbers and punctuation contains at least two.");
        [QMUITips showError:errorTitleMsg detailText:errorSub inView:self.view hideAfterDelay:[QMUITips smartDelaySecondsForTipsText:errorSub]];
        return false;
    }
    
    return true;
}
- (void)requestRegisterUserCheckAction {//BCCheckRegisterUserRequest
    [self.view showLoginToast];
    BCCheckRegisterUserRequest *request= [BCCheckRegisterUserRequest new];
    //
    request.field = self.inputView.account;
    WEAK_SELF
    [request didRequestSuccessed:^(id result, id page) {
        [wself requestCaptchaAction];
    }];
    [request didRequestFailed:^(NSError *error) {
        //        wself.nextStepButton.buttonStatus = GSCommonButtonStatusNormal;
        [wself.view hideLoginToast];
        if (error&&wself.view) {
            NSString *msg = error.domain;
            [QMUITips showError:msg inView:wself.view hideAfterDelay:[QMUITips smartDelaySecondsForTipsText:msg]];
        }
    }];
    [request requestServer];
}
//发送验证码
- (void)requestCaptchaAction {
    NSString *account = self.inputView.account;
    GSCCommonLoginAccountType type = [NSString gscLoginAccountTypeWithString:account];
    if (type==GSCCommonLoginAccountTypePhone) {
        [self requestPhoneCaptcha:account];
    }else if (type==GSCCommonLoginAccountTypeEmail) {
        [self requestEmailCaptchaAddress:account];
    }else {
        //        self.nextStepButton.buttonStatus = GSCommonButtonStatusNormal;
        [self.view hideLoginToast];
        if (self.view) {
            NSString *msg = @"Software Bug";
            [QMUITips showError:msg inView:self.view hideAfterDelay:[QMUITips smartDelaySecondsForTipsText:msg]];
        }
    }
}
//发送手机验证码
- (void)requestPhoneCaptcha:(NSString *)phone {//BCPhoneCaptchaRequest
    BCPhoneCaptchaRequest *requst = [BCPhoneCaptchaRequest new];
    requst.phone = phone;
    //
    WEAK_SELF
    [requst didRequestCompleted:^{
        //        wself.nextStepButton.buttonStatus = GSCommonButtonStatusNormal;
        [wself.view hideLoginToast];
    }];
    [requst didRequestSuccessed:^(id result, id page) {
        [wself requestRegisterSuccessAction];
    }];
    [requst didRequestFailed:^(NSError *error) {
        if (error&&wself.view) {
            NSString *msg = error.domain;
            [QMUITips showError:msg inView:wself.view hideAfterDelay:[QMUITips smartDelaySecondsForTipsText:msg]];
        }
    }];
    [requst requestServer];
}
//发送邮箱验证码
- (void)requestEmailCaptchaAddress:(NSString *)email {//BCEmailCaptchaRequest
    BCEmailCaptchaRequest *request = [BCEmailCaptchaRequest new];
    request.email = email;
    WEAK_SELF
    [request didRequestCompleted:^{
        //        wself.nextStepButton.buttonStatus = GSCommonButtonStatusNormal;
        [wself.view hideLoginToast];
    }];
    [request didRequestSuccessed:^(id result, id page) {
        [wself requestRegisterSuccessAction];
    }];
    [request didRequestFailed:^(NSError *error) {
        if (error) {
            NSString *msg = error.domain;
            [QMUITips showError:msg inView:wself.view hideAfterDelay:[QMUITips smartDelaySecondsForTipsText:msg]];
        }
    }];
    [request requestServer];
}


//账户验证成功并且已经发送验证码 跳转
- (void)requestRegisterSuccessAction {
    //更新数据
    [GSCommonLoginDataManager sharedData].registerModel.username = self.inputView.account;
    [GSCommonLoginDataManager sharedData].registerModel.bindUserAccount = self.inputView.account;
    [GSCommonLoginDataManager sharedData].registerModel.password = self.inputView.password;
    //
    GSComomRegisterSMSVerifyController *verifyVC = [GSComomRegisterSMSVerifyController new];
    [self.navigationController pushViewController:verifyVC animated:true];
}

@end
